package org.example.message.controller;

import org.example.message.entity.Message;
import org.example.entity.Base.Result;
import org.example.message.service.MessageService;
import org.example.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/message")
@Validated
public class MessageController {
    private final MessageService messageService;

    public MessageController(MessageService messageService) {
        this.messageService = messageService;
    }

    @GetMapping("/list")
    public Result list(HttpServletRequest request,String to) {
        String token=request.getHeader("Authorization");
        Map<String, Object> c= JWTUtil.parseToken(token);
        String from=(String)(c.get("Email"));
        System.out.println(from);
       List<Message> list= messageService.list(from,to);
        return Result.success(list);
    }
    @PostMapping("/addMessage")
    public Result addMessage(HttpServletRequest request, @RequestBody Map<String, String> requestBody) {
        String to = requestBody.get("to");
        String content = requestBody.get("content");
        String token = request.getHeader("Authorization");
        Map<String, Object> c = JWTUtil.parseToken(token);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// 设置纳秒部分，保留最多6位微秒
        timestamp.setNanos(timestamp.getNanos() / 1000 * 1000);
        Message message = new Message(null,(String)(c.get("Email")), to, 1, content, timestamp.toString());
        messageService.addMessage(message);
        return Result.success(message);
    }
    @GetMapping("/getGroupMessage")
    public Result getGroupMessage(String to) {
        return Result.success(messageService.getGroupMessage(to));
    }
    @PostMapping("/addGroupMessage")
    public Result addGroupMessage(HttpServletRequest request, @RequestBody Map<String, String> requestBody) {
        String to = requestBody.get("to");
        String content = requestBody.get("content");
        String token = request.getHeader("Authorization");
        Map<String, Object> c = JWTUtil.parseToken(token);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// 设置纳秒部分，保留最多6位微秒
        timestamp.setNanos(timestamp.getNanos() / 1000 * 1000);
        Message message = new Message(null,(String)c.get("Email"),to, 3, content, timestamp.toString());
        messageService.addMessage(message);
        return Result.success(message);
    }
}
